package com.yxj.checksystempicture.v;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.yxj.checksystempicture.R;
import com.yxj.checksystempicture.i.OnItemClickListener;
import com.yxj.checksystempicture.u.FileTypeUtils;
import java.util.ArrayList;
import java.util.List;

public class CheckPictureView extends FrameLayout {

    private RecyclerView recyclerView;
    private GridLayoutManager gridLayoutManager;
    /**
     * 默认显示多少列
     */
    private int listColumn = 3;

    /**
     * 适配器
     */
    private CheckAdapter adapter;

    /**
     * 默认选择图片
     */
    private int defaultImage = R.drawable.icon_default_check;

    /**
     * 最大选择数量
     * <p>
     * 默认最大 9
     */
    private int maxCheckCount = 9;

    /**
     * 数组数据
     */
    private List<CheckPictureBean> checkList = new ArrayList<>();

    /**
     * 设置数量
     *
     * @param column
     */
    @SuppressLint("NotifyDataSetChanged")
    public void setColumn(int column) {
        this.listColumn = column;
        if (gridLayoutManager != null) {
            gridLayoutManager.setSpanCount(column);
            recyclerView.setLayoutManager(gridLayoutManager);
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    public CheckPictureView(@NonNull Context context) {
        this(context, null);
    }

    public void setMaxCheckCount(int maxCheckCount) {
        this.maxCheckCount = maxCheckCount;
    }

    public CheckPictureView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    private int viewWidth;

    public CheckPictureView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttr(context, attrs, defStyleAttr);
        initDefaultImage();
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (viewWidth == 0) {
                    viewWidth = getMeasuredWidth();
                    if (viewWidth != 0) {
                        getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        initListView();
                    }
                }
            }
        });
    }


    /**
     * 自定义属性
     *
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    private void initAttr(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CheckPictureView, 0, defStyleAttr);
        maxCheckCount = array.getInt(R.styleable.CheckPictureView_maxCheckCount, 9);
        listColumn = array.getInt(R.styleable.CheckPictureView_listColumn,3);
        defaultImage = array.getResourceId(R.styleable.CheckPictureView_defaultImage,R.drawable.icon_default_check);
        array.recycle();
    }



    private void initListView() {
        recyclerView = new RecyclerView(getContext());
        gridLayoutManager = new GridLayoutManager(getContext(), listColumn);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(adapter = new CheckAdapter(checkList));
        recyclerView.setNestedScrollingEnabled(false);
        addView(recyclerView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    }


    /**
     * 初始化默认图
     */
    private void initDefaultImage() {
        CheckPictureBean checkPictureBean = new CheckPictureBean();
        checkPictureBean.isDefaultImage = true;
        checkPictureBean.defaultImage = defaultImage;
        checkList.add(checkPictureBean);
    }


    /**
     * 默认图片
     *
     * @param icon
     */
    public void setDefaultCheckImg(int icon) {
        for (CheckPictureBean checkPictureBean : checkList) {
            if (checkPictureBean.isDefaultImage) {
                checkPictureBean.defaultImage = icon;
                break;
            }
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 添加图或者视频
     *
     * @param path
     */
    public void addPath(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        CheckPictureBean checkPictureBean = new CheckPictureBean();
        checkPictureBean.path = path;
        if (FileTypeUtils.isVideoFile(path)) {
            checkPictureBean.pathType = 2;
        } else {
            checkPictureBean.pathType = 1;
        }
        checkList.add(0, checkPictureBean);
        adapter.notifyDataSetChanged();
        callBack();
    }



    private void callBack() {
        List<CheckPictureBean> l = new ArrayList<>();
        for (CheckPictureBean item:checkList) {
            if (!item.isDefaultImage){
                l.add(item);
            }
        }
        if (checkResultListener!=null){
            checkResultListener.onCheckResult(l);
        }
    }


    /**
     *
     */
    public class CheckAdapter extends RecyclerView.Adapter<CheckViewHolder> {
        List<CheckPictureBean> checkList;

        public CheckAdapter(List<CheckPictureBean> checkList) {
            this.checkList = checkList;
        }

        @NonNull
        @Override
        public CheckViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new CheckViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_check_picture, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull CheckViewHolder holder, int position) {

            ViewGroup.LayoutParams p = holder.itemView.getLayoutParams();
            p.width = p.height = viewWidth / listColumn;
            holder.itemView.setLayoutParams(p);

            CheckPictureBean item = checkList.get(position);
            holder.imRemove.setVisibility(item.isDefaultImage ? GONE : VISIBLE);
            holder.imPlay.setVisibility(item.pathType == 2 ? VISIBLE : GONE);

            if (item.isDefaultImage) {
                if (!TextUtils.isEmpty(item.path)) {
                    showImg(holder.image, item.path);
                } else {
                    showImg(holder.image, item.defaultImage);
                }
            } else {
                showImg(holder.image, item.path);
            }

            holder.imRemove.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    checkList.remove(item);
                    callBack();
                    notifyDataSetChanged();
                }
            });

            holder.image.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    /**
                     * 最大限制数量
                     */
                    if (checkList.size() > maxCheckCount) {
                        Toast.makeText(getContext(), "不能超出最大限值！", Toast.LENGTH_LONG).show();
                        return;
                    }

                    if (onItemClickListener != null) {
                        onItemClickListener.onItemClick(item);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return checkList.size();
        }
    }

    private void showImg(ImageView image, Object path) {
        Glide.with(getContext()).load(path).into(image);
    }

    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }


    private CheckResultListener checkResultListener;
    public void setCheckResultListener(CheckResultListener checkResultListener) {
        this.checkResultListener = checkResultListener;
    }

    public static class CheckViewHolder extends RecyclerView.ViewHolder {
        public ImageView image;
        public ImageView imRemove;
        public ImageView imPlay;

        public CheckViewHolder(@NonNull View itemView) {
            super(itemView);
            image = itemView.findViewById(R.id.image);
            imRemove = itemView.findViewById(R.id.imRemove);
            imPlay = itemView.findViewById(R.id.imPlay);
        }
    }


    public static class CheckPictureBean {
        /**
         * 图片路径
         */
        public String path;
        /**
         * 图片或者视频
         * 1 图
         * 2 视频
         */
        public int pathType;
        /**
         * 默认的图
         */
        public boolean isDefaultImage;
        /**
         * 默认的图
         */
        public int defaultImage;
    }

    public interface CheckResultListener{
        /**
         * 选择图片
         *
         * @param list
         */
        void onCheckResult(List<CheckPictureBean> list) ;
    }
}
